from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtSql import *
import Ui_unit
import master.utility as utility
import unitEdit

class Unit(QDialog, Ui_unit.Ui_unitDlg):
  def __init__(self, dbConn, dataGlob,  parent=None):
        super(Unit, self).__init__(parent)
        self.setupUi(self)
        self.initMenu()
        self.db = dbConn
        self.dataGlob = dataGlob
        self.util = utility.Utility(self.db)
        
        self.mastModel = QSqlQueryModel(self)
        self.mastModel.setHeaderData(1, Qt.Horizontal, QVariant("Unit"))
        self.mastModel.setHeaderData(2, Qt.Horizontal, QVariant("Unit Name"))
        self.mastModel.setHeaderData(3, Qt.Horizontal, QVariant("Unit Type"))
        self.mastModel.setHeaderData(4, Qt.Horizontal, QVariant("SQRM"))
        self.mastModel.setHeaderData(5, Qt.Horizontal, QVariant("FL"))
        self.mastModel.setHeaderData(6, Qt.Horizontal, QVariant("Owner"))
        self.mastModel.setHeaderData(7, Qt.Horizontal, QVariant("Tenant"))
        self.mastModel.setHeaderData(8, Qt.Horizontal, QVariant("Phone"))
        self.mastModel.setHeaderData(9, Qt.Horizontal, QVariant("Category"))
        self.mastModel.setHeaderData(10, Qt.Horizontal, QVariant("OPEN"))
        self.mastModel.setHeaderData(11, Qt.Horizontal, QVariant("RENT"))
        self.mastModel.setHeaderData(12, Qt.Horizontal, QVariant("SOLD"))
        self.mastModel.setHeaderData(13, Qt.Horizontal, QVariant("ELC"))
        self.mastModel.setHeaderData(14, Qt.Horizontal, QVariant("WTR"))
        self.mastModel.setHeaderData(15, Qt.Horizontal, QVariant("GAS"))
        self.mastModel.setHeaderData(16, Qt.Horizontal, QVariant("SC"))
        self.mastModel.setHeaderData(17, Qt.Horizontal, QVariant("SF"))
        
        self.master_tbv.setModel(self.mastModel)
        self.master_tbv.setItemDelegate(MasterDelegate(self))
        self.master_tbv.setSelectionMode(QTableView.SingleSelection)
        self.master_tbv.setSelectionBehavior(QTableView.SelectRows)
        self.connect(self.master_tbv.selectionModel(), SIGNAL("currentRowChanged(QModelIndex,QModelIndex)"), self.rowChanged)
        
        self.billModel = QSqlQueryModel(self)
        self.billModel.setHeaderData(0, Qt.Horizontal, QVariant("Bill Type"))
        self.billModel.setHeaderData(1, Qt.Horizontal, QVariant("Tarif ID"))
        self.billModel.setHeaderData(2, Qt.Horizontal, QVariant("Capacity (VA)"))
        self.billModel.setHeaderData(3, Qt.Horizontal, QVariant("CT"))
        self.billModel.setHeaderData(4, Qt.Horizontal, QVariant("Usage Trf (Rp)"))
        self.billModel.setHeaderData(5, Qt.Horizontal, QVariant("No Meter"))
        self.billModel.setHeaderData(6, Qt.Horizontal, QVariant("Bill To"))
        self.billModel.setHeaderData(7, Qt.Horizontal, QVariant("Billed"))
        
        self.billing_tbv.setModel(self.billModel)
        self.billing_tbv.setSelectionMode(QTableView.SingleSelection)
        self.billing_tbv.setSelectionBehavior(QTableView.SelectRows)
        
        self.joinModel = QSqlQueryModel(self)
        self.joinModel.setHeaderData(0, Qt.Horizontal, QVariant("Unit Join"))
        
        self.joinUnit_tbv.setModel(self.joinModel)
        self.joinUnit_tbv.setSelectionMode(QTableView.SingleSelection)
        self.joinUnit_tbv.setSelectionBehavior(QTableView.SelectRows)
        
        self.areaModel = QSqlQueryModel(self)
        self.areaModel.setHeaderData(0, Qt.Horizontal, QVariant("Floor"))
        self.areaModel.setHeaderData(1, Qt.Horizontal, QVariant("Sqrm"))
        self.areaModel.setHeaderData(2, Qt.Horizontal, QVariant("SC Tarif"))
        self.areaModel.setHeaderData(3, Qt.Horizontal, QVariant("SF Tarif"))
        
        self.detailArea_tbv.setModel(self.areaModel)
        self.detailArea_tbv.setSelectionMode(QTableView.SingleSelection)
        self.detailArea_tbv.setSelectionBehavior(QTableView.SelectRows)
        
        self.dataTagih = {"1":"Owner", "2":"Tenant", "3":"Developer"}
        self.dataJoin = {"N":"No Join", "G":"Group Join", "J":"Join To Other"}
        
        
  @pyqtSignature("")
  def on_unit_le_editingFinished(self):
      if self.unit_le.text() != "":
          self.unit_cb.setCheckState(Qt.Checked)
      else:
          self.unit_cb.setCheckState(Qt.Unchecked)
        
  @pyqtSignature("")
  def on_nama_le_editingFinished(self):
      if self.nama_le.text() != "":
          self.nama_cb.setCheckState(Qt.Checked)
      else:
          self.nama_cb.setCheckState(Qt.Unchecked)
          
  @pyqtSignature("")
  def on_owner_le_editingFinished(self):
      if self.owner_le.text() != "":
          self.owner_cb.setCheckState(Qt.Checked)
      else:
          self.owner_cb.setCheckState(Qt.Unchecked)
          
  @pyqtSignature("")
  def on_tenant_le_editingFinished(self):
      if self.tenant_le.text() != "":
          self.tenant_cb.setCheckState(Qt.Checked)
      else:
          self.tenant_cb.setCheckState(Qt.Unchecked)
          
  @pyqtSignature("")
  def on_desc_le_editingFinished(self):
      if self.desc_le.text() != "":
          self.desc_cb.setCheckState(Qt.Checked)
      else:
          self.desc_cb.setCheckState(Qt.Unchecked)
          
  @pyqtSignature("")
  def on_tipe_le_editingFinished(self):
      if self.tipe_le.text() != "":
          self.tipe_cb.setCheckState(Qt.Checked)
      else:
          self.tipe_cb.setCheckState(Qt.Unchecked)
          
  @pyqtSignature("")
  def on_floor_cmb_editingFinished(self):
      self.floor_cb.setCheckState(Qt.Checked)          
          
  def initMenu(self):
      self.retrieveAct = QAction(QIcon(":/retrieve.ico"), self.tr("Retrieve"), self)
#      self.retrieveAct.setShortcut ("Ctrl+R")
      self.connect(self.retrieveAct, SIGNAL("triggered()"), self.retrieveData)
      self.sortAct = QAction(QIcon(":/sort.ico"), self.tr("Sort"), self)
#      self.sortAct.setShortcut ("Ctrl+S")
      self.addAct = QAction(QIcon(":/add.ico"), self.tr("Add"), self)
#      self.addAct.setShortcut ("Ctrl+A")
      self.connect(self.addAct, SIGNAL("triggered()"), self.addData)
      self.editAct = QAction(QIcon(":/edit.ico"), self.tr("Edit"), self)
#      self.editAct.setShortcut ("Ctrl+E")
      self.connect(self.editAct, SIGNAL("triggered()"), self.editData)
      
      self.saveAct = QAction(QIcon(":/save.ico"), self.tr("Save History"), self)
      self.connect(self.saveAct, SIGNAL("triggered()"), self.saveHistory)
      
      self.delAct = QAction(QIcon(":/del.ico"), self.tr("Delete"), self)
      self.connect(self.delAct, SIGNAL("triggered()"), self.delData)
#      self.delAct.setShortcut ("Ctrl+Del")
      self.printAct = QAction(QIcon("res/print.ico"), self.tr("Print Preview"), self)
      self.connect(self.printAct, SIGNAL("triggered()"), self.printData)
#      self.printAct.setShortcut ("Ctrl+P")

  def retrieveData(self):
      qStr = "SELECT  u.kode_unit, u.unit ,u.nama_unit ,t.nama_tu ,u.luas_unit ,u.floor ,p.nama_pemilik_penyewa ,p2.nama_pemilik_penyewa ,u.tlp_unit ,b.nama_bu ,u.buka ,u.status_srd ,u.status_jual ,u.stat_bill_elc ,u.stat_bill_air ,u.stat_bill_gas ,u.stat_bill_sc ,u.stat_bill_sf FROM base_unit u "\
      "left outer join master_type_unit t on t.kode_tu = u.kode_tu "\
      "left outer join master_bisnis_unit b on b.kode_bu = u.kode_bu "\
      "left outer join master_pemilik_penyewa p on p.kode_pemilik_penyewa = u.owner "\
      "left outer join master_pemilik_penyewa p2 on p2.kode_pemilik_penyewa = u.tenant "
      
      filt = ""
      urut = " order by u.unit "
      if self.unit_cb.checkState() == Qt.Checked:
          filt = filt + " u.unit like '"+self.unit_le.text()+"%' and "
      if self.nama_cb.checkState() == Qt.Checked:
          filt = filt + " u.nama_unit like '"+self.nama_le.text()+"%' and "
#      if self.desc_cb.checkState() == Qt.Checked:
#          filt = filt + " m.desk_jurnal like '"+self.desc_le.text()+"%' and "
      if self.owner_cb.checkState() == Qt.Checked:
          filt = filt + " p.nama_pemilik_penyewa like '"+self.owner_le.text()+"%' and "
      if self.tenant_cb.checkState() == Qt.Checked:
          filt = filt + " p2.nama_pemilik_penyewa like '"+self.tenant_le.text()+"%' and "
          
      if filt != "":
          filt = " where "+filt.left(len(filt)-4)
          
      qStr = qStr + filt + urut
      self.mastModel.setQuery(qStr, self.db)
      self.master_tbv.setColumnHidden(0, True)
      self.master_tbv.setColumnWidth(1, 80)
      self.master_tbv.resizeRowsToContents()
      
  def addData(self):
      form = unitEdit.UnitEdit(self.db, "add",  self.dataGlob, self)
      form.show()

  def editData(self):
      index = self.master_tbv.currentIndex()
      if index.isValid():
          brs = self.mastModel.record(index.row())
          id = brs.value("kode_unit").toString()
          form = unitEdit.UnitEdit(self.db, id, self.dataGlob, self)
          form.show()

  def saveHistory(self):
      pesan = QMessageBox.question(self, "Unit", "Save history unit?", QMessageBox.Yes|QMessageBox.No)
      if pesan == QMessageBox.Yes:
          skr = self.util.getServerToday().date().toString("yyyy-MM-dd")
          query = QSqlQuery()
          query.exec_("select count(*) from base_unit_hist where periode = '"+skr+"'")
          query.next()
          hist = query.value(0).toInt()[0]
          if hist > 0:
              QMessageBox.warning(self, "Unit", "History unit has been save today!")
          else:
              query.exec_("insert into base_unit_hist select *,'"+skr+"' from base_unit")
              query.exec_("insert into base_unit_hist_bill select *,'"+skr+"' from base_unit_det_bill")
              query.exec_("insert into base_unit_hist_area select *,'"+skr+"' from base_unit_det_unit")
              query.exec_("insert into base_unit_hist_det select *,'"+skr+"' from base_unit_detail")
              QMessageBox.information(self, "Unit", "Saving unit history succeed!")

  def delData(self):
      index = self.master_tbv.currentIndex()
      if index.isValid():
          brs = self.mastModel.record(index.row())
          id = brs.value("kode_unit").toString()
          nama = brs.value("unit").toString()
          if QMessageBox.question(self, "Unit","Delete Unit : "+nama+"?", QMessageBox.Yes|QMessageBox.No) == QMessageBox.Yes:
              qMast = QSqlQuery(self.db)
              qBill = QSqlQuery(self.db)
              qArea = QSqlQuery(self.db)
              qJoin = QSqlQuery(self.db)
              self.db.transaction()
              qBill.exec_("delete from base_unit_det_bill where kode_unit = '"+id+"'")
              qArea.exec_("delete from base_unit_det_unit where kode_unit = '"+id+"'")
              qJoin.exec_("delete from base_unit_detail where kode_unit = '"+id+"'")
              qMast.exec_("delete from base_unit where kode_unit = '"+id+"'")
              self.db.commit()
              self.retrieveData()
              self.rowChanged()

  def sortData(self):
       qStr = "select id_pelanggan, kode_pelanggan, nama, no_kartu, alamat1, kota1 from pelanggan"
       self.mastModel.setQuery(qStr, self.db)

  def printData(self):
      self.dialog = QPrintPreviewDialog()
      self.connect(self.dialog, SIGNAL("paintRequested(QPrinter *)"), self.printPreview)
      self.dialog.exec_()
       
  def printPreview(self,  printer):
      painter = QPainter()
      painter.begin(printer)
      index = self.master_tbv.currentIndex()
      if not index.isValid():
          return
      brs = self.mastModel.record(index.row())
      id = brs.value("kode_unit").toString()
      myfont = QFont("Arial", 11)
      painter.setFont(myfont)
      painter.end()
      
  def contextMenuEvent(self, event):
        menu = QMenu(self)
        menu.addAction(self.retrieveAct)
        menu.addAction(self.sortAct)
        menu.addSeparator()
        menu.addAction(self.addAct)
        menu.addAction(self.editAct)
        menu.addSeparator()
        menu.addAction(self.saveAct)
        menu.addSeparator()
        menu.addAction(self.delAct)
        menu.addSeparator()
        menu.addAction(self.printAct)
        menu.exec_(event.globalPos())

  def rowChanged(self):
      index = self.master_tbv.currentIndex()
      if not index.isValid():
          return
      record = self.mastModel.record(index.row())
      id = record.value("kode_unit").toString()
      
      qStr = "select d.tipe_tagih, d.kode_tarif, t.tarif_daya, t.rasio, t.tarif_satuan, d.no_meter, p.nama_pemilik_penyewa, d.billed from base_unit_det_bill d "\
      "left outer join master_pemilik_penyewa p on p.kode_pemilik_penyewa = d.kode_pemilik_penyewa "\
      "left outer join master_tarif_detail t on t.kode_tarif = d.kode_tarif "\
      "where d.kode_unit = '"+id+"'"
      self.billModel.setQuery(qStr, self.db)
      self.billing_tbv.resizeRowsToContents()
      
      qStr = "select m.unit from base_unit_detail d "\
      "left outer join base_unit m on m.kode_unit = d.unit_join "\
      "where d.kode_unit = '"+id+"'"
      self.joinModel.setQuery(qStr, self.db)
      
      qStr = "select lantai, luas, harga_sc, harga_sf from base_unit_det_unit d "\
      "where d.kode_unit = '"+id+"'"
      self.areaModel.setQuery(qStr, self.db)
      
      query = QSqlQuery(self.db)      
      qStr = "select unit, kode_tu, nama_unit, luas_unit , bast, awal_sewa, akhir_sewa, kode_bu, tlp_unit, buka, floor, status_srd, awal_fitout, akhir_fitout, sc_bill_to, util_bill_to, owner, status_join, note , kode_unit, join_to, tenant, usaha, desc_unit , status_jual, tgl_jual, stat_bill_elc, stat_bill_air, stat_bill_gas, stat_bill_sc, stat_bill_sf from base_unit where kode_unit = '"+id+"'"
      query.exec_(qStr)
      while query.next():
          scto = self.dataTagih[unicode(query.value(14).toString())]
          self.scto_cmb.setCurrentIndex(self.scto_cmb.findText(scto, Qt.MatchExactly))
          utilto = self.dataTagih[unicode(query.value(15).toString())]
          self.utilto_cmb.setCurrentIndex(self.utilto_cmb.findText(utilto, Qt.MatchExactly))
          self.open_cb_2.setCheckState(Qt.Checked if query.value(9).toString() == "1" else Qt.Unchecked)
          self.ho_de.setDate(query.value(4).toDate())
          self.sold_cb_2.setCheckState(Qt.Checked if query.value(24).toString() == "Y" else Qt.Unchecked)
          self.sold_de.setDate(query.value(25).toDate())
          self.rent_cb_2.setCheckState(Qt.Checked if query.value(11).toString() == "Y" else Qt.Unchecked)
          self.rentStart_de.setDate(query.value(5).toDate())
          self.rentEnd_de.setDate(query.value(6).toDate())
          self.fitStart_de.setDate(query.value(12).toDate())
          self.fitEnd_de.setDate(query.value(13).toDate())
          join = self.dataJoin[unicode(query.value(17).toString())]
          self.join_cmb.setCurrentIndex(self.join_cmb.findText(join, Qt.MatchExactly))
          self.note_le.setText(unicode(query.value(18).toString()))
          self.desc_te.setHtml(query.value(23).toString())      
          owner = unicode(query.value(16).toString())
          tenant = unicode(query.value(21).toString())
      
      self.idO_le.setText(owner)
      qStr = "select nama_pemilik_penyewa, concat(alamat_pemilik_penyewa,' ',kota_pemilik_penyewa,' ',kode_pos), no_telp, no_fax, no_ponsel, nama_pt, concat(alamat_pt,' ',kota_pt), no_telp_pt, no_fax_pt, email, kode_tt, id_no, npwp from master_pemilik_penyewa where kode_pemilik_penyewa = '"+owner+"'"
      query.exec_(qStr)
      while query.next():
          self.nameO_le.setText(query.value(0).toString())
          self.addrO_le.setText(query.value(1).toString())
          self.typeO_le.setText(query.value(10).toString())
          self.emailO_le.setText(query.value(9).toString())
          self.phoneO_le.setText(query.value(2).toString())         
          self.faxO_le.setText(query.value(3).toString())
          self.hpO_le.setText(query.value(4).toString())
          self.idCardO_le.setText(query.value(11).toString())
          self.taxO_le.setText(query.value(12).toString())
          self.compO_le.setText(query.value(5).toString())
          self.addr2O_le.setText(query.value(6).toString())
          self.phone2O_le.setText(query.value(7).toString())
          self.fax2O_le.setText(query.value(8).toString())
       
      self.idT_le.setText(tenant)
      qStr = "select nama_pemilik_penyewa, concat(alamat_pemilik_penyewa,' ',kota_pemilik_penyewa,' ',kode_pos), no_telp, no_fax, no_ponsel, nama_pt, concat(alamat_pt,' ',kota_pt), no_telp_pt, no_fax_pt, email, kode_tt, id_no, npwp from master_pemilik_penyewa where kode_pemilik_penyewa = '"+tenant+"'"
      query.exec_(qStr)
      while query.next():
          self.nameT_le.setText(query.value(0).toString())
          self.addrT_le.setText(query.value(1).toString())
          self.typeT_le.setText(query.value(10).toString())
          self.emailT_le.setText(query.value(9).toString())
          self.phoneT_le.setText(query.value(2).toString())
          self.faxT_le.setText(query.value(3).toString())
          self.hpT_le.setText(query.value(4).toString())
          self.idCardT_le.setText(query.value(11).toString())
          self.tax_le.setText(query.value(12).toString())
          self.compT_le.setText(query.value(5).toString())
          self.addr2T_le.setText(query.value(6).toString())
          self.phone2T_le.setText(query.value(7).toString())
          self.fax2T_le.setText(query.value(8).toString())
          
  def hitungTotal(self):
      totBrs = self.mastModel.rowCount()
#      rpTot = 0
#      poinTot = 0
#      for i in range(totBrs):
#          record = self.mastModel.record(i)
#          rpTot += record.value(TOTAL_RP).toDouble()[0]
#          poinTot += record.value(POIN).toDouble()[0]
#      self.totalRp.setText(str(rpTot))
#      self.totalPoin.setText(str(poinTot))

class MasterDelegate(QItemDelegate):
    def __init__(self, parent=None):
        super(MasterDelegate, self).__init__(parent)
        
    def paint(self, painter, option, index):
        myoption = QStyleOptionViewItem(option)
        if index.column() == 0:
            myoption.displayAlignment |= Qt.AlignRight|Qt.AlignVCenter
        QItemDelegate.paint(self, painter, myoption, index)        
            
class DetailDelegate(QItemDelegate):
    def __init__(self, parent=None):
        super(DetailDelegate, self).__init__(parent)
        
    def paint(self, painter, option, index):
        myoption = QStyleOptionViewItem(option)
        if index.column() == 3 or index.column() == 4:
            myoption.displayAlignment |= Qt.AlignRight|Qt.AlignVCenter
        QItemDelegate.paint(self, painter, myoption, index)
        
if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    form = Unit()
    form.show()
    app.exec_()
